// DOM Elements
const appContainer = document.getElementById('app-container');
const sidebarToggle = document.getElementById('sidebar-toggle');
const chatForm = document.getElementById('chat-form');
const promptInput = document.getElementById('prompt-input');
const imageUpload = document.getElementById('image-upload');
const chatWindow = document.getElementById('chat-window');
const newChatButton = document.getElementById('new-chat-button');
const conversationList = document.getElementById('conversation-list');
const modelSelector = document.getElementById('model-selector');
const modeSelector = document.getElementById('mode-selector');
const imagePreviewContainer = document.getElementById('image-preview-container'); // 3. 新增DOM引用
const audioUpload = document.getElementById('audio-upload');
const audioPreviewContainer = document.getElementById('audio-preview-container');
let currentConversationId = null;
audioUpload.addEventListener('change', handleAudioSelection);
// --- Event Listeners ---
document.addEventListener('DOMContentLoaded', loadConversations);
sidebarToggle.addEventListener('click', () => appContainer.classList.toggle('sidebar-collapsed'));
newChatButton.addEventListener('click', () => switchConversation(null));
chatForm.addEventListener('submit', handleFormSubmit);

// 3. 新增: 监听文件选择事件以生成预览
imageUpload.addEventListener('change', handleImageSelection);

promptInput.addEventListener('input', e => { e.target.style.height = 'auto'; e.target.style.height = (e.target.scrollHeight) + 'px'; });
promptInput.addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); chatForm.dispatchEvent(new Event('submit')); } });


//用户管理
// 获取DOM元素
const userManagementButton = document.getElementById('user-management-button');
const userPanel = document.getElementById('user-panel');
const logoutButton = document.getElementById('logout-button');

// 用户面板显示/隐藏控制
userManagementButton.addEventListener('click', (e) => {
  e.stopPropagation();
  // userManagementButton.style.color = '#91dc62'; // 设置为红色，可根据需要修改颜色值
  userPanel.classList.toggle('show');
});

// 点击页面其他区域关闭用户面板
document.addEventListener('click', (e) => {
  if (!userPanel.contains(e.target) && e.target !== userManagementButton) {
    userPanel.classList.remove('show');
  }
});

// 登出功能
logoutButton.addEventListener('click', () => {
  // 这里添加登出逻辑
  fetch('/logout', {
    method: 'POST'
  }).then(() => {
    window.location.href = '/login';
  });
});
let userName = '用户'
// 加载用户信息
async function loadUserInfo() {
  try {
    const response = await fetch('/user_info');
    const userData = await response.json();
    const userManagementButtonSpan = document.getElementById('user-management-button-span');
    document.getElementById('username').textContent = userData.user_name;
    userName = userData.user_name;
    userManagementButtonSpan.textContent = userName;  // 正确
    document.getElementById('user-email').textContent = userData.user_mail;
    // alert(`欢迎您，${userData.user_name}${userData.user_mail}`)
    if (userData.avatar) {
      document.querySelectorAll('.user-avatar, .user-avatar-large').forEach(img => {
        img.src = userData.avatar;
      });
    }
  } catch (error) {
    console.error('Error loading user info:', error);
  }
}

// 页面加载时获取用户信息
document.addEventListener('DOMContentLoaded', loadUserInfo);

//---模式选择--
modeSelector.addEventListener('change', () => {
    const selectedMode = modeSelector.value;
    if (selectedMode === '点击选择模式') {
        return;
    }else if (selectedMode === '普通聊天') {
        window.location.href = '/chat_page'; // 普通聊天页面
    } else if (selectedMode === 'RAG') {
        window.location.href = '/chat_rag_page'; // RAG 页面
    }
    
     // 延迟重置，防止阻塞跳转
    setTimeout(() => {
        modeSelector.value = 'NULL';
    }, 100);
});


// 替换图片图标为Font Awesome的相机图标（通过SVG路径）
document.querySelector('#image-upload + button svg').innerHTML =
    '<path d="M4 4h7V2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2v-7h-2v7H4V4z"/>';

// 替换音频图标为麦克风图标
document.querySelector('#audio-upload + button svg').innerHTML =
    '<path d="M12 2a3 3 0 0 1 3 3v6a3 3 0 0 1-6 0V5a3 3 0 0 1 3-3z"/>';

imageUpload.addEventListener('change', function() {
    if (this.files.length > 0) {
        document.querySelector('#image-upload + button svg').innerHTML =
            '<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z"/>'; // 勾选图标
    }
});

//----RAG知识库的管理
let selectedKnowledgeBase = null; // 存储当前选择的知识库名

// 显示弹窗
document.getElementById('open-kb-modal').addEventListener('click', () => {
    document.getElementById('knowledge-base-modal').style.display = 'block';
    loadKnowledgeBases(); // 加载知识库列表
});

// 提交创建知识库
document.getElementById('create-kb-btn').addEventListener('click', async () => {
    const kbName = document.getElementById('kb-name').value.trim();
    const files = document.getElementById('kb-files').files;

    if (!kbName || files.length === 0) {
        alert('请填写知识库名称并选择文件');
        return;
    }

    const formData = new FormData();
    formData.append('kb_name', kbName);
    for (let i = 0; i < files.length; i++) {
        formData.append('files', files[i]);
    }
    // 在长时间操作时添加加载指示器
    document.getElementById('create-kb-btn').disabled = true;
    const response = await fetch('/chat_rag/build_knowledge_base', {
        method: 'POST',
        body: formData
    });
    document.getElementById('create-kb-btn').disabled = false;
    if (response.ok) {
        alert('知识库创建成功');
        // 清空表单
        document.getElementById('kb-name').value = '';
        document.getElementById('kb-files').value = '';
        // 刷新知识库列表
        await loadKnowledgeBases();
    } else {
        alert('创建知识库失败');
    }
});

// 加载知识库列表
async function loadKnowledgeBases() {
    try {
        const response = await fetch('/chat_rag/get_all_knowledge_base');
        const data = await response.json(); // 后端返回的是 ["kb1", "kb2"]

        const list = document.getElementById('kb-list');
        list.innerHTML = ''; // 清空旧内容

        if (Array.isArray(data)) {
            data.forEach(kbName => {
                const div = document.createElement('div');
                div.style.cursor = 'pointer';
                div.textContent = kbName; // 直接显示知识库名称

                div.addEventListener('click', () => {
                    selectedKnowledgeBase = kbName;
                    document.getElementById('selected-kb-name').textContent = kbName;
                    document.getElementById('selected-kb-name-on-toolbar').textContent = kbName;
                });

                list.appendChild(div);
            });
        } else {
            console.error("获取到的知识库数据不是数组");
        }
    } catch (error) {
        console.error('加载知识库失败:', error);
    }
}


// 确认操作
// 修改知识库选择确认逻辑
// 修改删除知识库逻辑
document.getElementById('confirm-kb-action').addEventListener('click', async () => {
    const action = document.querySelector('input[name="kb-action"]:checked').value;

    if (!selectedKnowledgeBase) {
        alert('请先选择一个知识库');
        return;
    }

    if (action === 'select') {
        // 更新UI显示
        document.getElementById('selected-kb-name').textContent = selectedKnowledgeBase;
        document.getElementById('selected-kb-name-on-toolbar').textContent = selectedKnowledgeBase;
        // 关闭弹窗
        document.getElementById('knowledge-base-modal').style.display = 'none';
        // 显示成功提示
        alert(`已选择知识库 "${selectedKnowledgeBase}"`)
    } else if (action === 'delete') {
        const confirmDelete = confirm(`确定要删除知识库 "${selectedKnowledgeBase}" 吗？`);
        if (confirmDelete) {
            const response = await fetch('/chat_rag/delete_knowledge_base', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ kb_name: selectedKnowledgeBase })
            });

            const result = await response.json();
            if (result.success) {
                alert('知识库删除成功');
                // 刷新知识库列表
                await loadKnowledgeBases();
                // 重置选择
                selectedKnowledgeBase = null;
                document.getElementById('selected-kb-name').textContent = '';
                document.getElementById('selected-kb-name-on-toolbar').textContent = '';
                localStorage.removeItem('selectedKnowledgeBase');
            } else {
                alert('删除失败: ' + (result.error || '未知错误'));
            }
        }
    }
});
// 页面加载时恢复知识库选择
document.addEventListener('DOMContentLoaded', () => {
    const savedKB = localStorage.getItem('selectedKnowledgeBase');
    if(savedKB) {
        selectedKnowledgeBase = savedKB;
        document.getElementById('selected-kb-name').textContent = savedKB;
        document.getElementById('selected-kb-name-on-toolbar').textContent = savedKB;
    }
    loadConversations();
});

// 是否开启文生图
let isTxt2ImgEnabled = false;
document.getElementById('enable-txt2img').addEventListener('change', function(e) {
    let isTxt2ImgEnabled = e.target.checked;
    // 根据开关状态执行不同操作
    if (isTxt2ImgEnabled) {
        console.log('Txt2Img is enabled');
        isTxt2ImgEnabled = true;
    }
    if (!isTxt2ImgEnabled) {
        console.log('Txt2Img is disabled');
        isTxt2ImgEnabled = false;
    }
});

// --- Core Functions ---
//加载历史对话
async function loadConversations() {
    try {
        //接口: GET /api/conversations
        //const response = await fetch('/api/conversations', {method: ''POST});
        const response = await fetch('/chat_rag/load_conversations');
        const conversations = await response.json();
        conversationList.innerHTML = '';
        conversations.forEach(conv => {
            const li_button_div = document.createElement('div');
            li_button_div.style.display = 'flex';       // 启用 Flex 布局
            li_button_div.style.justifyContent = 'space-between'; // 左右两端对齐
            li_button_div.style.alignItems = 'center';  // 垂直居中
            li_button_div.style.width = '100%';         // 确保宽度填满父容器

            const li = document.createElement('li');
            li.textContent = conv.title;
            li.dataset.id = conv.id;
            li.style.cursor = 'pointer';
            li.style.margin = '0';                      // 清除默认 margin
            li.style.flexGrow = '1';                    // 允许 li 填充剩余空间

            const button = document.createElement('button');
            button.textContent = '✖';
            button.style.backgroundColor = '#DFF0FE';
            button.style.color = 'black';
            button.style.border = 'none';
            button.style.borderRadius = '5px';
            button.style.padding = '4px 8px';
            button.style.cursor = 'pointer';
            button.style.marginLeft = '10px';           // 增加左侧间距

            // 事件监听
            li.addEventListener('click', () => switchConversation(conv.id));
            button.addEventListener('click', (e) => {
                e.stopPropagation(); // 阻止事件冒泡到 li
                deleteConversation(conv.id);
            });

            // 组装元素
            li_button_div.appendChild(li);
            li_button_div.appendChild(button);
            conversationList.appendChild(li_button_div);
        });
        updateActiveConversationVisuals();
    } catch (error) { console.error("Error loading conversations:", error); }
}

async function switchConversation(conversationId) {
    currentConversationId = conversationId;
    //清空聊天窗口
    chatWindow.innerHTML = '';


    if (conversationId) {
        try {
            //接口: GET /api/conversation/:id
            const response = await fetch(`/chat_rag/switch_conversation/?id=${conversationId}&&kb=${selectedKnowledgeBase}`);
            const history = await response.json();
            history.forEach(message => {
                const role = message.role === 'user' ? 'user' : 'ai';
                let content;

                // 检查是否为字符串且需要转换
                if (typeof message.content === 'string') {
                    try {
                        content = JSON.parse(message.content.replace(/'/g, '"'));
                    } catch (e) {
                        content = message.content; // 回退到原始内容
                    }
                } else {
                    content = message.content; // 已经是对象
                }

                // 根据内容类型显示消息
                if (content.image_url) {
                    displayMessage(role, content.description, null, null, false, content.image_url);
                } else {
                    displayMessage(role, content);
                }
            });
        } catch (error) { console.error("Error switching conversation:", error); }
    }
    promptInput.focus();
    updateActiveConversationVisuals();
}
async function deleteConversation(conversationId) {
    const confirmDelete = confirm("确定要删除该记录吗?");
    if (!confirmDelete) {
        return; // 如果用户点击取消，中止删除操作
    }
    currentConversationId = conversationId;
    //清空聊天窗口
    chatWindow.innerHTML = '';


    if (conversationId) {
        try {
            //接口: GET /api/conversation/:id
            const response = await fetch(`/chat_rag/delete_conversation/?id=${conversationId}&&kb=${selectedKnowledgeBase}`);
            const data = await response.json();
            if(data.success){
                //  // 删除成功后刷新对话列表
                await loadConversations();
                updateActiveConversationVisuals(); // 更新高亮状态
            }
        } catch (error) { console.error("Error daleting conversation:", error); }
    }
    promptInput.focus();
    updateActiveConversationVisuals();
    await loadConversations(); // 注意首字母大写
}
//聊天的信息的提交
async function handleFormSubmit(event) {
    event.preventDefault();
    const prompt = promptInput.value.trim();
    const imageFiles = imageUpload.files;
    const audioFiles = audioUpload.files;

    // 修复条件判断
    if (!prompt && !imageFiles.length && !audioFiles.length) return;

    // 创建文件引用副本
    const filesToDisplay = {
        images: imageFiles.length > 0 ? Array.from(imageFiles) : null,
        audios: audioFiles.length > 0 ? Array.from(audioFiles) : null
    };

    displayMessage('user', prompt, filesToDisplay.images, filesToDisplay.audios);
    scrollToBottom();

    const formData = new FormData();
    formData.append('prompt', prompt);
    formData.append('model', modelSelector.value);

    // 图片文件处理
    if (imageFiles.length > 0) {
        for (let i = 0; i < imageFiles.length; i++) {
            formData.append('images', imageFiles[i]);
        }
    }

    // 音频文件处理（修复循环变量）
    if (audioFiles.length > 0) {
        for (let i = 0; i < audioFiles.length; i++) {
            formData.append('audios', audioFiles[i]);
        }
    }

    if (currentConversationId) {
        formData.append('conversation_id', currentConversationId);
    }

    // 在formData.append('enable_txt2img', ...)之后添加：
    if (selectedKnowledgeBase) {
        formData.append('selectedKnowledgeBase', selectedKnowledgeBase);  // 确保与后端字段名匹配
    }

    //增加是否开启文生图
    formData.append('enable_txt2img', document.getElementById('enable-txt2img').checked)

    // 清空表单
    promptInput.value = '';
    promptInput.style.height = 'auto';
    imageUpload.value = '';
    audioUpload.value = '';
    imagePreviewContainer.innerHTML = '';
    audioPreviewContainer.innerHTML = '';

    try {
        const response = await fetch('/chat_rag', {
            method: 'POST',
            body: formData
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();

        if (data.new_conversation_created) {
            currentConversationId = data.conversation_id;
            await loadConversations();
        }
        if (data.image_url){
            displayMessage('ai', data.response,null,null,false,data.image_url);
            // console.log(data.image_url)

        }
        else {
            displayMessage('ai', data.response);
        }
    } catch (error) {
        console.error('Error:', error);
        displayMessage('ai', `**Error:** ${error.message}`, null, null, true);
    } finally {
        scrollToBottom();
    }
}



// --- UI Helper Functions ---

// 处理音频选择和预览
function handleAudioSelection(event) {
  audioPreviewContainer.innerHTML = '';
  const files = event.target.files;

  if (files && files.length > 0) {
      Array.from(files).forEach(file => {
          if (!file.type.match('audio.*')) return;

          const wrapper = document.createElement('div');
          wrapper.className = 'audio-preview-wrapper';

          // 音频元素
          const audio = document.createElement('audio');
          audio.src = URL.createObjectURL(file);
          audio.controls = true;
          audio.style.width = '100%';

          // 删除按钮
          const removeBtn = document.createElement('button');
          removeBtn.className = 'audio-preview-remove-btn';
          removeBtn.textContent = '×';
          removeBtn.onclick = () => {
              wrapper.remove();
              updateFileInput(file);
          };

          wrapper.appendChild(audio);
          wrapper.appendChild(removeBtn);
          audioPreviewContainer.appendChild(wrapper);
      });
  }

  function updateFileInput(fileToRemove) {
      const newFiles = Array.from(audioUpload.files).filter(f => f !== fileToRemove);
      const dataTransfer = new DataTransfer();
      newFiles.forEach(f => dataTransfer.items.add(f));
      audioUpload.files = dataTransfer.files;
  }
}




// 3. 新增: 处理图片选择和预览的函数
function handleImageSelection(event) {
    imagePreviewContainer.innerHTML = ''; // 清空旧预览
    const file = event.target.files[0];

    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const wrapper = document.createElement('div');
            wrapper.className = 'img-preview-wrapper';

            const img = document.createElement('img');
            img.src = e.target.result;
            img.title = file.name;

            const removeBtn = document.createElement('button');
            removeBtn.className = 'img-preview-remove-btn';
            removeBtn.textContent = '×';
            removeBtn.title = 'Remove image';
            removeBtn.onclick = function() {
                imageUpload.value = ''; // 清空文件输入
                imagePreviewContainer.innerHTML = ''; // 移除预览
            };

            wrapper.appendChild(img);
            wrapper.appendChild(removeBtn);
            imagePreviewContainer.appendChild(wrapper);
        }
        reader.readAsDataURL(file);
    }
}



function displayMessage(role, content, imageFiles = null,audioFiles=null, isError = false,  imageUrl=null){
    const wrapper = document.createElement('div');
    wrapper.className = `message-wrapper ${role}`;

    const avatar = document.createElement('div');
    avatar.className = 'avatar';
    avatar.textContent = role === 'user' ? 'You' : 'AI';

    const messageDiv = document.createElement('div');
    messageDiv.className = 'message';
    // messageDiv.style.borderRadius = '30px'; // 添加圆角样式

    if (isError) {
        messageDiv.style.backgroundColor = '#ffdddd';
        messageDiv.style.color = '#d8000c';
    }

    // 1. 修改: 关键修复点
    if (content) {
        if (role === 'ai') {
            // AI 的回复内容通过 marked.js 解析为 HTML
            messageDiv.innerHTML = marked.parse(content);
        } else {
            // 用户的输入内容强制作为纯文本处理，防止 HTML 注入和显示错乱
            // 浏览器会自动处理换行符，因为 .message 的 CSS 有 white-space: pre-wrap;
            messageDiv.textContent = content;
    }
    }
    if (imageUrl){
        if(role === 'ai'){
            const img = document.createElement('img');
            img.src = imageUrl;
            img.style.maxWidth = '250px';
            img.style.borderRadius = '12px';
            messageDiv.appendChild(img);

        }
    }
    if (imageFiles) {

        for (let i = 0; i < imageFiles.length; i++) {
            const img = document.createElement('img');
            img.src = URL.createObjectURL(imageFiles[i]);
            img.style.maxWidth = '250px';
            img.style.borderRadius = '12px';
            img.style.marginTop = content ? '10px' : '0'; // 如果有文字，则增加间距
            img.style.display = 'block';
            messageDiv.appendChild(img);
        }
    }

    // 新增音频预览处理
    if (audioFiles) {
        for (let i = 0; i < audioFiles.length; i++) {
            const audio = document.createElement('audio');
            audio.src = typeof audioFiles[i] === 'string'
              ? audioFiles[i]
              : URL.createObjectURL(audioFiles[i]);
            audio.controls = true;
            audio.style.width = '100%';
            audio.style.marginTop = '10px';
            messageDiv.appendChild(audio);
        }
    }

    wrapper.appendChild(avatar);
    wrapper.appendChild(messageDiv);
    chatWindow.appendChild(wrapper);

    // 确保 hljs 对新插入的AI消息中的代码块进行高亮
    if (role === 'ai') {
        messageDiv.querySelectorAll('pre code').forEach(el => {
            hljs.highlightElement(el);        });
    }
}

function updateActiveConversationVisuals() {
    document.querySelectorAll('#conversation-list li').forEach(li => {
        li.classList.toggle('active', li.dataset.id === currentConversationId);
    });
}

function scrollToBottom() {
    chatWindow.scrollTop = chatWindow.scrollHeight;
}